import { View } from '@tarojs/components';
import s from './index.module.scss'
import { useEffect, useState } from 'react';
import Taro from '@tarojs/taro';


export default function Index() {
  const [elementX, setElementX] = useState(0)
  const [elementY, setElementY] = useState(0)
  const [touchMoveX, setTouchMoveX] = useState(0)
  const [touchMoveY, setTouchMoveY] = useState(0)
 

  function touchstart(e) {
    setTouchMoveX(e.touches[0].clientX);
    setTouchMoveY(e.touches[0].clientY);
  }
  
  function touchmove(e: any) {
    // 问：差值是如何计算的
    // 1. 移动后的位置减去移动前的位置
    // 2. 移动后的位置用代码怎么表示
    // 3. 移动前的位置怎么表示
    const disX = e.touches[0].clientX - touchMoveX
    const disY = e.touches[0].clientY - touchMoveY

    setTouchMoveX(e.touches[0].clientX);
    setTouchMoveY(e.touches[0].clientY);

    setElementX(elementX + disX)
    setElementY(elementY + disY)
  }

  useEffect(() => {
    //获取元素的初始位置
    const query = Taro.createSelectorQuery()
    query.select('#draggable').boundingClientRect((res) => {
      // @ts-ignore
      setElementX(res.left)
      // @ts-ignore
      setElementY(res.top)
    }).exec()
  }, [])


  return (
    <View className={s.wrapper}>
      <View className={s.container}> 
        <View 
        className={s.touch}
          onTouchStart={touchstart}
          onTouchMove={touchmove}
          id='draggable'
          style={{left: elementX , top: elementY }}
        ></View>
     </View>
    </View>
  )
}